﻿using MediatR;
using SqlSugar;
using Warehouse.ErrorCord;
using Warehouse.Read.Api.Actions.Command.WarehouseCategory;
using Warehouse.Read.Api.DTO;

namespace Warehouse.Read.Api.Actions.CommandHandel.WarehouseCategory
{
    public class GetWarehouseCommandHandle : IRequestHandler<GetWarehouseCommand, APIResult<APIPaging<Warehouse.Domain.WarehouseCategory>>>
    {
        private readonly ISqlSugarClient db;

        public GetWarehouseCommandHandle(ISqlSugarClient db)
        {
            this.db = db;
        }

        public Task<APIResult<APIPaging<Warehouse.Domain.WarehouseCategory>>> Handle(GetWarehouseCommand request, CancellationToken cancellationToken) 
        {
            APIResult<APIPaging<Warehouse.Domain.WarehouseCategory>> result = new APIResult<APIPaging<Warehouse.Domain.WarehouseCategory>>();
            var list = db.Queryable<Warehouse.Domain.WarehouseCategory>().Where(x=>x.IsDel==false).ToList();
            if (request.WarehouseTypeId!=0)
            {
                list = list.Where(a => a.WarehouseTypeId == request.WarehouseTypeId).ToList();
            }
            APIPaging<Warehouse.Domain.WarehouseCategory> page = new APIPaging<Domain.WarehouseCategory>();
            page.TotalCount = list.Count();
            page.PageCount = Math.Ceiling(list.Count() * 1.0 / request.PageSize);
            page.list=list.OrderByDescending(a => a.WarehouseTypeId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";
            result.Data = page;
            return Task.FromResult(result);
        }
    }
}
